<?php

class class_category {

    public function doList($table) {
        $lists = $_ENV['db']->fetchAll("SELECT class_id, CONCAT( path,',',class_id ) AS path, parent_id, sort, class_name FROM `{$table}` ORDER BY path,sort");

        foreach ((array)$lists as $k=>$row) {
            $deep = count(explode(',',$row['path']))-1;

            $row['class_name'] = $deep == 1 ? $row['class_name'] : (str_repeat('&nbsp;&nbsp;',$deep).'└'.$row['class_name']);
            $lists[$k] = $row;
        }

        return (array)$lists;
    }
	
	//判断节点是否有孩子节点 add by txz 2012-2-2
	public function IsHaveChild($table,$pid)
	{
		$isHave = false;
		$lists = $_ENV['db']->fetchAll("SELECT path FROM `{$table}` ORDER BY path,sort");

        foreach ((array)$lists as $k=>$row) 
		{
            $paths = explode(',',$row['path']);
			if(in_array($pid,$paths))
			{
				 $isHave = true;
				 break;
			}
        }
        return $isHave;
	}

    public function add($table,$class_name,$parent_id,$sort) {
        if (!$sort || !preg_match('/^[0-9]+$/',$sort)) {
            $sort = 0;
        }

        if (0 != $parent_id) {
            $class = $_ENV['db']->fetch("SELECT * FROM {$table} WHERE `class_id` = '{$parent_id}'");
            if (!$class) return false;
            $path = $class['path'].','.$parent_id;
        } else {
            $path = '0';
        }

        $_ENV['db']->runSql("INSERT INTO `{$table}` SET `class_name` = '{$class_name}', `parent_id` = '{$parent_id}', `sort` = '{$sort}',`path` = '{$path}'");

        return $_ENV['db']->insertId();
    }

    public function modi($table,$class_id,$class_name,$parent_id,$sort) {
        if (!$sort || !preg_match('/^[0-9]+$/',$sort)) {
            $sort = 0;
        }

        if (0 != $parent_id) {
            $class = $_ENV['db']->fetch("SELECT * FROM {$table} WHERE `class_id` = '{$parent_id}'");
            if (!$class) return false;
            $path = $class['path'].','.$parent_id;
        } else {
            $path = '0';
        }

        $_ENV['db']->runSql("UPDATE `{$table}` SET `class_name` = '{$class_name}', `parent_id` = '{$parent_id}', `sort` = '{$sort}', `path` = '{$path}' WHERE `class_id` = '{$class_id}'");
        return true;
    }
}